package com.xiaoma.myaudience.biz.view;

import java.lang.ref.WeakReference;
import java.util.List;

import android.content.Context;
import android.graphics.Rect;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xiaoma.myaudience.R;
import com.xiaoma.myaudience.biz.model.CategoryOptionInfo;
import com.xiaoma.myaudience.biz.model.QuickAction;
import com.xiaoma.myaudience.biz.view.MyHorizontalScrollView.onScrollChangedListener;

public class OptionBar extends QuickActionWidget {

    private MyHorizontalScrollView mTypeScrollView;
    private MyHorizontalScrollView mAreaScrollView;
    private Button mConfirmButton;

    private List<QuickAction> mQuickActions;
	private OnConfirmButtonClickListener mOnConfirmButtonClickListener;
	private LinearLayout mLoadingLayout;
	private LinearLayout mLoadFailedLayout;
	private ImageView mTypeLeftArrow;
	private ImageView mTypeRightArrow;
	private ImageView mAreaLeftArrow;
	private ImageView mAreaRightArrow;
	private LinearLayout mTypeLayout;
	private LinearLayout mAreaLayout;
	private OptionBarContainer mContainer;
    
    /**
     * 
     * 
     * @author chen xin
     */
    public static interface OnConfirmButtonClickListener {

        void OnConfirmButtonClicked(View v);
    }
    
	public void setOnConfirmButtonClickListener(OnConfirmButtonClickListener listener) {
		mOnConfirmButtonClickListener = listener;
	}

	public final OnConfirmButtonClickListener getOnConfirmButtonClickListener() {
		return mOnConfirmButtonClickListener;
	}

    public OptionBar(Context context) {
        super(context);
 
        mContainer = new OptionBarContainer(context);
        mContainer.addView(LayoutInflater.from(context).inflate(R.layout.option_bar, null));
        setContentView(mContainer);

        final View v = getContentView();
        mTypeLayout = (LinearLayout) v.findViewById(R.id.type_layout);
        mAreaLayout = (LinearLayout) v.findViewById(R.id.area_layout);
        //mConfirmButton = (Button) v.findViewById(R.id.option_bar_confirm_button);
        mLoadingLayout = (LinearLayout) v.findViewById(R.id.option_bar_loading_layout);
        mLoadFailedLayout = (LinearLayout) v.findViewById(R.id.option_bar_loading_failed_layout);
        mLoadingLayout.setVisibility(View.GONE);
        mLoadFailedLayout.setVisibility(View.GONE);
        
        mTypeScrollView = (MyHorizontalScrollView) v.findViewById(R.id.option_bar_type_scrollview);
        mAreaScrollView = (MyHorizontalScrollView) v.findViewById(R.id.option_bar_area_scrollview);
        
        mTypeLeftArrow = (ImageView) v.findViewById(R.id.option_bar_left_button1);
        mTypeRightArrow = (ImageView) v.findViewById(R.id.option_bar_right_button1);     
        mAreaLeftArrow = (ImageView) v.findViewById(R.id.option_bar_left_button2);
        mAreaRightArrow = (ImageView) v.findViewById(R.id.option_bar_right_button2);
        
        setArrowOffsetY(-10);
        setClickListener();
        setBackgroundDrawable(null);
    }
    
    private class OptionBarContainer extends FrameLayout {

        public OptionBarContainer(Context context) {
            super(context);
        }

        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                dismiss();
                return true;
            } else if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
                dismiss();
                return true;
            } else {
                return super.dispatchKeyEvent(event);
            }
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            final int x = (int) event.getX();
            final int y = (int) event.getY();
            
            if ((event.getAction() == MotionEvent.ACTION_DOWN)
                    && ((x < 0) || (x >= getWidth()) || (y < 0) || (y >= getHeight()))) {
                dismiss();
                return true;
            } else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                dismiss();
                return true;
            } else {
                return super.onTouchEvent(event);
            }
        }

    }
    
    private void setClickListener() {   	
    	//mConfirmButton.setOnClickListener(mComfirmListener);
    	mTypeScrollView.setOnScrollChangedListener(mTypeOnScrollChangedListener);
    	mAreaScrollView.setOnScrollChangedListener(mAreaOnScrollChangedListener);
    }
    
    /**
     * 确认按钮的监听
     */
    private OnClickListener mComfirmListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if(mOnConfirmButtonClickListener != null) {
				mOnConfirmButtonClickListener.OnConfirmButtonClicked(v);
			}
            if (getDismissOnClick()) {
                dismiss();
            }
		}
    };
    
    /**
     * HorizontalScrollView的滚动监听
     */
    private onScrollChangedListener mTypeOnScrollChangedListener = new onScrollChangedListener() {
		@Override
		public void onScrollChanged() {
			// TODO Auto-generated method stub
			setDirectionArrowStatus(mTypeScrollView, mTypeLeftArrow, mTypeRightArrow);
		}
    };
    
    private onScrollChangedListener mAreaOnScrollChangedListener = new onScrollChangedListener() {
		@Override
		public void onScrollChanged() {
			// TODO Auto-generated method stub
			setDirectionArrowStatus(mAreaScrollView, mAreaLeftArrow, mAreaRightArrow);
		}
    };
    
    private int mTypeScrollViewRealWidth = -1;
    private int mAreaScrollViewRealWidth = -1;
    
    /**
     * 重置HorizontalScrollView的实际宽度
     */
    private void resetHorizontalScrollViewRealWidth() {
        mTypeScrollViewRealWidth = -1;
        mAreaScrollViewRealWidth = -1;
    }
    
    /**
     * 获取HorizontalScrollView的实际宽度值
     * @param anchor
     * @return
     */
    private int getHorizontalScrollViewRealWidth(HorizontalScrollView anchor) {
    	int totalWidth = 0;
    	if(anchor == mTypeScrollView && mTypeScrollViewRealWidth != -1) totalWidth = mTypeScrollViewRealWidth;
    	else if(anchor == mAreaScrollView && mAreaScrollViewRealWidth != -1) totalWidth = mAreaScrollViewRealWidth;
    	else {
            ViewGroup child = (ViewGroup) anchor.getChildAt(0);
            if (child != null) {
            	int count = child.getChildCount();
            	if(count > 0) {
            		for(int i=0; i<count; i++) {
            			totalWidth += child.getChildAt(i).getMeasuredWidth();
            		}
            		
            	}
            	if(anchor == mTypeScrollView) mTypeScrollViewRealWidth = totalWidth;
            	else mAreaScrollViewRealWidth = totalWidth;
                
            }
    	}
        return totalWidth;
    }
    
    /**
     * @return 如果HorizontalScrollView能滚动，返回true
     */
    private boolean canScroll(HorizontalScrollView anchor) {        
        ViewGroup child = (ViewGroup) anchor.getChildAt(0);
        if (child != null) {
            return anchor.getWidth() < getHorizontalScrollViewRealWidth(anchor) + anchor.getPaddingLeft() + anchor.getPaddingRight() ;
        }
        return false;
    }
    
    /**
     * 判断HorizontalScrollView是否滚动到最右端
     * @param anchor
     * @return
     */
    private boolean canScrollToRight(HorizontalScrollView anchor) {
        ViewGroup child = (ViewGroup) anchor.getChildAt(0);
        if (child != null) {
        	int count = child.getChildCount();
        	int responseWidth = 0;
        	if(count > 0) {
        		//右滚动阀值为实际总宽度减去最后一个item的一半宽度
        		responseWidth = getHorizontalScrollViewRealWidth(anchor) - child.getChildAt(count - 1).getMeasuredWidth()/2;
        	}
            return anchor.getScrollX() + anchor.getWidth() < responseWidth;
        }
        return false;
    }
    
    /**
     * 判断HorizontalScrollView是否滚动到最左端
     * @param anchor
     * @return
     */
    private boolean canScrollToLeft(HorizontalScrollView anchor) {
        ViewGroup child = (ViewGroup) anchor.getChildAt(0);
        if (child != null) {
        	int count = child.getChildCount();
        	int responseWidth = 0;
        	if(count > 0) {
        		//左滚动阀值第一个item宽度的一半
        		responseWidth = child.getChildAt(0).getMeasuredWidth()/2;
        	}
            return anchor.getScrollX() > responseWidth;
        }
        return false;
    }
    
    /**
     * 设置方向箭头是否显示
     * @param anchor
     * @param leftArrow
     * @param rightArrow
     */
    private void setDirectionArrowStatus(HorizontalScrollView anchor, ImageView leftArrow, ImageView rightArrow) {
        if(!canScroll(anchor)) {
        	leftArrow.setVisibility(View.INVISIBLE);
        	rightArrow.setVisibility(View.INVISIBLE);
        } else {
        	leftArrow.setVisibility(View.VISIBLE);
        	rightArrow.setVisibility(View.VISIBLE);
        	
            if(canScrollToRight(anchor) && canScrollToLeft(anchor)){
            	leftArrow.setVisibility(View.VISIBLE);
            	rightArrow.setVisibility(View.VISIBLE);
            } else if(!canScrollToRight(anchor) && canScrollToLeft(anchor)) {
            	leftArrow.setVisibility(View.VISIBLE);
            	rightArrow.setVisibility(View.INVISIBLE);
            } else if(canScrollToRight(anchor) && !canScrollToLeft(anchor)) {
            	leftArrow.setVisibility(View.INVISIBLE);
            	rightArrow.setVisibility(View.VISIBLE);
            }
        }  
    }
        
    public void showLoadingView() {
    	mLoadingLayout.setVisibility(View.VISIBLE);
        mLoadFailedLayout.setVisibility(View.GONE);
    }

    public void showFailedView() {
    	mLoadingLayout.setVisibility(View.GONE);
        mLoadFailedLayout.setVisibility(View.VISIBLE);
    }
    
    public void showContentView() {
    	mLoadingLayout.setVisibility(View.GONE);
        mLoadFailedLayout.setVisibility(View.GONE);
    }
    
    @Override
    public void show(View anchor) {
    	
        super.show(anchor);

        resetHorizontalScrollViewRealWidth();
        //显示的时候获取宽度
        getHorizontalScrollViewRealWidth(mTypeScrollView);
        getHorizontalScrollViewRealWidth(mAreaScrollView);
        //初始化箭头的显示状态
        setDirectionArrowStatus(mTypeScrollView, mTypeLeftArrow, mTypeRightArrow);
		setDirectionArrowStatus(mAreaScrollView, mAreaLeftArrow, mAreaRightArrow);
    }

    @Override
    protected void onMeasureAndLayout(Rect anchorRect, View contentView) {
        contentView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
        contentView.measure(MeasureSpec.makeMeasureSpec(getScreenWidth(), MeasureSpec.EXACTLY),
                LayoutParams.WRAP_CONTENT);

        int rootHeight = contentView.getMeasuredHeight();

        int offsetY = getArrowOffsetY();
        int dyTop = anchorRect.top;
        int dyBottom = getScreenHeight() - anchorRect.bottom;

        boolean onTop = (dyTop > dyBottom);
        int popupY = (onTop) ? anchorRect.top - rootHeight + offsetY : anchorRect.bottom - offsetY;

        setWidgetSpecs(popupY, onTop);
    }


    @Override
    protected void populateQuickActions(List<QuickAction> quickActions) {

        mQuickActions = quickActions;

        final LayoutInflater inflater = LayoutInflater.from(getContext());

        for (QuickAction action : quickActions) {
            TextView view = (TextView) inflater.inflate(R.layout.option_bar_item, null);
            view.setText(action.mTitle);
            view.setTag(action.mType);
            if(action.mIsSelected) view.setEnabled(false);
            else view.setEnabled(true);
           
            view.setOnClickListener(mClickHandlerInternal);
            if(action.mType.equals(CategoryOptionInfo.PARAM_TYPE)) 
            	mTypeLayout.addView(view, new LinearLayout.LayoutParams(
            			getContext().getResources().getDimensionPixelSize(R.dimen.option_bar_item_width), LayoutParams.FILL_PARENT, 1.0f));
            else if(action.mType.equals(CategoryOptionInfo.PARAM_AREA)) 
            	mAreaLayout.addView(view, new LinearLayout.LayoutParams(
            			getContext().getResources().getDimensionPixelSize(R.dimen.option_bar_item_width), LayoutParams.FILL_PARENT, 1.0f));
            action.mView = new WeakReference<View>(view);        
        }
    }

	@Override
    protected void onClearQuickActions() {
        super.onClearQuickActions();
        mTypeLayout.removeAllViews();
        mAreaLayout.removeAllViews();
    }

    private OnClickListener mClickHandlerInternal = new OnClickListener() {

        public void onClick(View view) {

            final OnQuickActionClickListener listener = getOnQuickActionClickListener();

            if (listener != null) {
                final int itemCount = mQuickActions.size();
                String type = view.getTag().toString();
                for (int i = 0; i < itemCount; i++) {
                	if(type.equals(mQuickActions.get(i).mType)) mQuickActions.get(i).mView.get().setEnabled(true);
                    if (view == mQuickActions.get(i).mView.get()) {  
                        listener.onQuickActionClicked(mQuickActions.get(i).mType, mQuickActions.get(i).mID, view);
                        //break;
                    } 
                }
            }
/*
            if (getDismissOnClick()) {
                dismiss();
            }*/
        }

    };

}